import axios from 'axios'
import store from '../store'
// import { getToken } from '../utils/auth'
import router from '../router'
import native from '@/libs/native/index';
import * as types from '../store/mutation-types';
// let baseURL = 'http://172.20.13.158:5000'; 
// let baseURL = 'http://172.20.41.18:5000'; //李强
// let baseURL = 'http://192.168.111.32:5000'; //测试
// let baseURL = 'http://172.20.41.141:8580'; // 吴俊
// let baseURL = 'http://172.20.13.62:8580'; //陈武
// let baseURL = 'http://172.20.13.165:8580'; //杨海龙
// let baseURL = 'http://172.20.19.129:8580'; // 蔡少东
let baseURL = 'http://192.168.111.51:8580'; // 测试
// let baseURL = 'https://gateway.xianchaoshop.com';

//  测试
if (location.host.indexOf("192.168.111.51") != -1) {
  baseURL = "http://192.168.111.51:8580";
};

//线上
if (location.host.indexOf("h5.xianchaoshop.com") != -1) {
  baseURL = "https://gateway.xianchaoshop.com";
};

//预发
if (location.host.indexOf("preh5.xianchaoshop.com") != -1) {
  baseURL = "https://pregateway.xianchaoshop.com";
};

// create an axios instance
let service = axios.create({
  baseURL: baseURL, // api的base_url
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {

  config.headers['X-Requested-With'] = 'XMLHttpRequest';

  // openId
  let openId = '';
  let hashObj = parseUrlHash(location.hash);
  if(hashObj.openId){
    openId = hashObj.openId;
    sessionStorage.setItem('openId',openId);
  }else{
    openId = sessionStorage.getItem('openId');
  };

  // 有openId走openId 没有就走token的
  if(openId){
    config.headers['openId'] = openId;
    config.headers['appId'] = 'ishangjie';
  }else{
    // token
    let token = localStorage.getItem('token');
    if (token) {
      config.headers['token'] = token;
    }else if(!store.state.isApp){
      config.headers['token']  = 'APP_TOKEN_98c424be-24a6-4983-bbc8-d61d673674d5';
    }
  }
  
 
  //马甲包
  if (!store.state.isApp) {
    let methodEnv = localStorage.getItem('methodEnv');
    if (methodEnv == 'h5') {
      if (config.data.methodEnv) {
        delete config.data.methodEnv;
      };
      config.data = {
        test: config.data
      };
    }
  };

  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => {
   
    if(response.data.code!='0000'){
      store.commit(types.SHOW_MSG, {
        content: response.data.msg
      });
    }
    //登陆过期 或者未登陆
    if(response.data.code=='9996'||response.data.code=='1003'){
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      native.goLogin();
    }
    return response.data
  },
  (error) => {
    return Promise.reject(error)
});

var parseUrlHash = (url)=>{
  let obj = {};
  let strArr1 = url.split('?');
  if(strArr1[1]){
    let strArr2 = strArr1[1].split('&');
    strArr2.forEach(item => {
      let strArr3 = item.split('=');
      obj[strArr3[0]] = strArr3[1];
    });
  };
  return obj;
}


var formatUrl = (url, data) => {
  if (!data) return url;
  if (typeof (data) === "string") {
    return url + data;
  }
  if (typeof (data) === "object") {
    for (var key in data) {
      var value = data[key];
      if (value === null) continue;
      var mark = "{" + key + "}";
      if (url.indexOf(mark) === -1) continue;
      url = url.replace(mark, value);
    };
    return url;
  }
  return url;
};
var request = function () {
  //   resource = formatUrl(resource, query);
  let params = {

  };
  if (arguments.length) {
    params = {
      ...arguments[0]
    }
  }
  // if (store.state.isApp) {
  //   return nativeFun(params);
  // } else {
    return service.apply(this, arguments);
  // }

};
service.get = (resource, query) => {
  return request(resource, query, null, "get");
}
service.post = (resource, data, query) => {
  return request(resource, query, data, "post");
}
service.put = (resource, data, query) => {
  return request(resource, query, data, "put");
}
let nativeFun = (params) => {
  // resource = formatUrl(resource, query);
  return new Promise(function (resolve, reject) {
    let obj = {
      url: params.url,
      params: params.data
    };

    return native.getForwardInfo(obj, 'no', {}).then(res => {
      res = JSON.parse(res);
      //toast提示
      if (res.status != '0000') {
        if (res.message)
          store.commit(types.SHOW_MSG, {
            content: res.message
          });
      }
      return resolve(res)
    })
  })
};
export {
  baseURL
}
export default request
